//
//  ChartView.m
//  YunGui
//
//  Created by Hanen 3G 01 on 16/4/5.
//  Copyright © 2016年 hanen. All rights reserved.
//

#import "ChartView.h"

#define radiansToDegrees(x) (180.0 * x / M_PI)

#define RandColor [UIColor colorWithRed:arc4random_uniform(256) / 255.0 green:arc4random_uniform(256) / 255.0 blue:arc4random_uniform(256) / 255.0 alpha:1.0]

@interface ChartView ()
{
    
    CGFloat radius ;
    //起始的角度
    CGFloat startAngle;
    //结束的角度
    CGFloat endAngle;
    CGFloat spaceAngle ;//空隙的角度
    UIView  *chartView;
    NSMutableArray  *_colorArr;
    
    NSMutableArray  *_precentArr;
    
    NSMutableAttributedString *attrbuteStr;
    UILabel        *_centerLabel;
    UILabel        *_typeLabel;
    
    UILabel        *_statistcNameLabel;
    
    
}
@property (nonatomic) CAShapeLayer *progressLayer;
@property (nonatomic) float progress;
@property (nonatomic, strong) NSMutableArray *endAngleArray;
@end


@implementation ChartView

- (id)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        _precentArr = [NSMutableArray array];
        _endAngleArray = [NSMutableArray array];
        
        radius = 75.0f;
        startAngle = 0;
        //结束的角度
        endAngle = 0;
        spaceAngle = M_PI * 0 / 360;//空隙的角度
        [self addInfoView];
    }
    return self;
}
- (void)addInfoView
{
    
    attrbuteStr = [[NSMutableAttributedString alloc] initWithString:@"93%"];
    [attrbuteStr setAttributes:@{NSFontAttributeName : [UIFont systemFontOfSize:20.0f]} range:NSMakeRange(0, attrbuteStr.length)];
    [attrbuteStr setAttributes:@{NSFontAttributeName : [UIFont systemFontOfSize:35.0f]} range:NSMakeRange(0, attrbuteStr.length - 1)];
    _centerLabel = [ViewTool getLabelWithFrame:CGRectMake(0, 0, 100, 50) WithAttrbuteString:attrbuteStr];
    _centerLabel.center = CGPointMake(self.width / 2.0f, self.height / 2.0f - 35.0f);
    _centerLabel.textAlignment = NSTextAlignmentCenter;
    _centerLabel.textColor = BlueColor;
    
    _typeLabel = [ViewTool getLabelWith:CGRectMake (_centerLabel.x, _centerLabel.maxY, _centerLabel.width, 20) WithTitle:@"COMPETITION" WithFontSize:14.0f WithTitleColor:GRAYCOLOR WithTextAlignment:NSTextAlignmentCenter];
    
    [self addSubview:_centerLabel];
    [self addSubview:_typeLabel];
    
    _statistcNameLabel = [ViewTool getLabelWith:CGRectMake (self.width / 2.0f - 50, self.height - 80 , 100, 20) WithTitle:@"竞争统计" WithFontSize:16.0f WithTitleColor:BLACKCOLOR WithTextAlignment:NSTextAlignmentCenter];
    [self addSubview:_statistcNameLabel];
}
- (void)setPrecentArray:(NSMutableArray *)precentArray
{
    _precentArray = precentArray;
    self.colorArray = [NSMutableArray array];
    
    NSLog(@"传入的百分比的个数 ：%ld",(unsigned long)precentArray.count);
    CGPoint point = CGPointMake(self.width / 2.0f, self.height / 2.0f - 30.0f);
    //        CGFloat radius = MIN(self.width, self.height) * 0.26;
    //        CGFloat radius = 75.0f;
    //起始的角度
    
    UIImageView *imageV = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, radius *2.7, radius *2.7)];
        imageV.center = point;
        imageV.image = [UIImage imageNamed:@"Btn_Normal_dian2"];
        [self addSubview:imageV];
    
    if (chartView) {
        [chartView removeFromSuperview];
    }
    chartView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, radius * 2.5, radius *2.5)];
    chartView.center = point;
//        chartView.backgroundColor = [UIColor orangeColor];
    
//    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)];
//    [chartView addGestureRecognizer:tap];
    [self addSubview:chartView];
    
    CGPoint chartPoint = CGPointMake(chartView.width / 2.0f, chartView.height / 2.0f);
    
    for (int i = 0; i <_precentArray.count; i++) {
        endAngle = ([self.precentArray[i] intValue] / 100.0) * (M_PI * 2 - (self.precentArray.count) * spaceAngle) + startAngle;
        [_endAngleArray addObject:@(endAngle)];
        
        UIColor *color = RandColor;
        [self.colorArray addObject:color];
        
        _progressLayer = [self createRingLayerWithCenter:chartPoint radius:radius lineWidth:15.0f color:color withStarAngle:startAngle withEndAngle:endAngle];
        [chartView.layer addSublayer:_progressLayer];
        startAngle = endAngle + spaceAngle;
        
        
        CABasicAnimation *strokeEndAnimation = nil;
        strokeEndAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
        strokeEndAnimation.duration = 0.35f;
        strokeEndAnimation.fromValue = @(0);
        strokeEndAnimation.toValue = @(1);
        strokeEndAnimation.autoreverses = NO; //无自动动态倒退效果
        strokeEndAnimation.delegate = self;
        
        [_progressLayer addAnimation:strokeEndAnimation forKey:@"strokeEnd"];
    }
    
    
    
    //            [_precentArr addObject:self.precentArray[i]];
    [self setNeedsDisplay];
    
    
    
}
- (void)handleTap:(UITapGestureRecognizer *)tap
{
    NSLog(@"点击了 图标");
    
    CGPoint point = [tap locationInView:chartView];//获得点击的point
    //判断点击的地方 在圆弧左右
    CGFloat maxXY = radius * 2 - 20 * 2;//减去线框
    CGPoint chartCenter = CGPointMake(chartView.width / 2.0f, chartView.height / 2.0f);
    
    if (ABS(point.x - chartCenter.x) < maxXY / 2.0f && ABS(point.y - chartCenter.y) < maxXY / 2.0f) {
        //触摸的地方落在 中心点 除圆弧以外的地方
        NSLog(@"触摸的地方落在 中心点 除圆弧以外的地方");
    }else{
        //        NSLog(@"触摸的地方落在 圆弧");
        CGFloat tapAngle = [self angleBetweenLineOne:chartCenter withLineOne:CGPointMake(chartView.width , chartView.height / 2.0f) withLineSecond:chartCenter withLineSecond:point];
        NSLog(@"触摸的地方落在 圆弧之前的 %f",tapAngle);
        //        if (tapAngle > 180) {
        //            tapAngle = (180 - tapAngle) + 180;
        //        }
        //           NSLog(@"触摸的地方落在 圆弧%f",tapAngle);
        //计算与初始的角度的偏差值
        //CGRectContainsPoint(CGRectMake(0, 0, chartView.width, chartView.height), point)
        //        if () {
        startAngle = 0;
        endAngle = 0;
        NSLog(@"%lu+++++----",(unsigned long)_endAngleArray.count);
        for (int i = 0; i < _endAngleArray.count; i++) {
            CGFloat endAng = 0;
            CGFloat endDegree = 0;
            CGFloat endAng1 = [_endAngleArray[i] floatValue];
            CGFloat endDegree1 = radiansToDegrees(endAng1);
            
            if(i == 0){
                endDegree = 0;
            }else{
                endAng = [_endAngleArray[i - 1] floatValue];
                endDegree = radiansToDegrees(endAng);
            }
            
            
            if (tapAngle >= endDegree && tapAngle < endDegree1) {
                NSString *str;
                if ([self.precentArray[i] floatValue] == 100) {
                   str = [NSString stringWithFormat:@"%.f",[self.precentArray[i] floatValue]];
                }else{
                   str = [NSString stringWithFormat:@"%.1f",[self.precentArray[i] floatValue]];
                }
                
                attrbuteStr = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@%%",str]];
                [attrbuteStr setAttributes:@{NSFontAttributeName : [UIFont systemFontOfSize:20.0f]} range:NSMakeRange(0, attrbuteStr.length)];
                [attrbuteStr setAttributes:@{NSFontAttributeName : [UIFont systemFontOfSize:35.0f]} range:NSMakeRange(0, attrbuteStr.length - 1)];
                _centerLabel.attributedText = attrbuteStr;
                
                _typeLabel.text = _compeleteArray[i];
                break;
            }
            //            NSLog(@"每个数组的 结束角度%f, 下一个角度 %f",endDegree,endDegree1);
        }
        //            for (int i = 0; i< self.precentArray.count; i++) {
        //                endAngle = radiansToDegrees(([self.precentArray[i] intValue] / 100.0) * (M_PI * 2 - (self.precentArray.count) * (spaceAngle / M_PI))) + startAngle;
        //                NSLog(@"开始角度 %f ---结束角度%f",startAngle,endAngle);
        //                if (( tapAngle) <= endAngle && ( tapAngle) > startAngle) {
        //                    attrbuteStr = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@%%",self.precentArray[i]]];
        //                    [attrbuteStr setAttributes:@{NSFontAttributeName : [UIFont systemFontOfSize:30.0f]} range:NSMakeRange(0, attrbuteStr.length)];
        //                    [attrbuteStr setAttributes:@{NSFontAttributeName : [UIFont systemFontOfSize:50.0f]} range:NSMakeRange(0, attrbuteStr.length - 1)];
        //                    _centerLabel.attributedText = attrbuteStr;
        //                    break;
        //                }
        //                        startAngle = endAngle + spaceAngle;
        //            }
        
        //        }
    }
}
//两条线计算 角度
- (CGFloat)angleBetweenLineOne:(CGPoint )pointOneStar
                   withLineOne:(CGPoint)pointOneEnd
                withLineSecond:(CGPoint)pointSecondStar
                withLineSecond:(CGPoint)pointSecondEnd
{
    CGFloat a = pointOneEnd.x - pointOneStar.x;
    CGFloat b = pointOneEnd.y - pointOneStar.y;
    
    CGFloat c = pointSecondEnd.x - pointSecondStar.x;
    CGFloat d = pointSecondEnd.y - pointSecondStar.y;
    CGFloat degree ;
    CGFloat rads = acos(((a*c) + (b*d)) / ((sqrt(a*a + b*b)) * (sqrt(c*c + d*d))));
    if (pointSecondEnd.y < pointOneEnd.y) {
        degree = (180 - radiansToDegrees(rads))+ 180;
    }else{
        degree = radiansToDegrees(rads);
    }
    
    //    NSLog(@"触摸的角度 %f",rads);
    return degree;
    
}
- (CAShapeLayer *)createRingLayerWithCenter:(CGPoint)center radius:(CGFloat)rad lineWidth:(CGFloat)lineWidth color:(UIColor *)color withStarAngle:(CGFloat) starAnglee withEndAngle:(CGFloat)endAnglee
{
    UIBezierPath *smoothedPath = [UIBezierPath bezierPathWithArcCenter:CGPointMake(radius, radius) radius:rad startAngle:starAnglee endAngle:endAnglee clockwise:YES];
    CAShapeLayer *slice = [CAShapeLayer layer];
    slice.contentsScale = [[UIScreen mainScreen] scale];
    slice.frame = CGRectMake(center.x - rad, center.y - rad, rad * 2, rad * 2);
    slice.fillColor = [UIColor clearColor].CGColor;
    slice.strokeColor = color.CGColor;
    slice.lineWidth = lineWidth;
    slice.lineCap = kCALineJoinBevel;
    slice.lineJoin = kCALineJoinBevel;
    slice.path = smoothedPath.CGPath;
    
    
    return slice;
}
- (void)setTitle:(NSString *)title{
    _title = title;
    _statistcNameLabel.text = _title;
    
}
- (void)setPercentStr:(NSString *)percentStr{
    _percentStr = percentStr;
    NSString *str;
    if ([_percentStr floatValue] == 100 ) {
        str = [NSString stringWithFormat:@"%.f",[_percentStr floatValue]];
    }else{
        str = [NSString stringWithFormat:@"%.1f",[_percentStr floatValue]];
    }
    attrbuteStr = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@%%",str]];
    [attrbuteStr setAttributes:@{NSFontAttributeName : [UIFont systemFontOfSize:20.0f]} range:NSMakeRange(0, attrbuteStr.length)];
    [attrbuteStr setAttributes:@{NSFontAttributeName : [UIFont systemFontOfSize:35.0f]} range:NSMakeRange(0, attrbuteStr.length - 1)];
    _centerLabel.attributedText = attrbuteStr;
}
- (void)setCompleteStr:(NSString *)completeStr{
    _completeStr = completeStr;
    _typeLabel.text = _completeStr;
}
//- (void)drawRect:(CGRect)rect
//{
//    CGContextRef context = UIGraphicsGetCurrentContext();
//
////    CGContextSetStrokeColorWithColor(context, RandColor.CGColor);
//    //设置中心点
//    CGPoint point = CGPointMake(self.width / 2.0f, self.height / 2.0f);
//    //半径
//    CGFloat radius = MIN(self.width, self.height) * 0.3;
//    //起始的角度
//    CGFloat startAngle = -M_PI *0.5;
//    //结束的角度
//    CGFloat endAngle;
//
//    //隔开 空隙的角度
//    CGFloat  spaceAngle = 5.0f;
//
//    for (int i = 0; i <_precentArr.count; i++) {
//        //每次都换 起始点 和结束点
//         endAngle = ([self.precentArray[i] intValue] / 100.0) * (M_PI * 2 ) + startAngle;
//        NSLog(@"起点角度%f  终点角度%f",startAngle,endAngle);
//
//        UIBezierPath *bezierPath = [UIBezierPath bezierPathWithArcCenter:point radius:radius startAngle:startAngle endAngle:endAngle clockwise:YES];
//
////        CAShapeLayer *layer = [CAShapeLayer layer];
////        layer.frame = CGRectMake(point.x - radius, point.y - radius, radius * 2, radius * 2);
////        layer.fillColor = [UIColor whiteColor].CGColor;
////        layer.strokeColor = RandColor.CGColor;
////        layer.lineWidth = 20.0f;
////        layer.lineCap = kCALineJoinBevel;
////        layer.lineJoin = kCALineJoinBevel;
////        layer.path = bezierPath.CGPath;
//
//        //设置线宽
//        CGContextSetLineWidth(context, 20.0f);
//        //添加path到context上
//        CGContextAddPath(context, bezierPath.CGPath);
//
//        CGContextSetStrokeColorWithColor(context, RandColor.CGColor);
//        CGContextStrokePath(context);
//
//        startAngle = endAngle;
//
//    }
//}

/*
 // Only override drawRect: if you perform custom drawing.
 // An empty implementation adversely affects performance during animation.
 - (void)drawRect:(CGRect)rect {
 // Drawing code
 }
 */

@end
